# coding=utf-8
"""
Created on 2018年09月11日
"""
import weakref
from service_base.article_service import ArticleService
from util_base.ufo_decorators import processor
from common_base.cmd import CMD
from processor_base.base_processor import BaseProcessor
from util_base.exception import ParamException, UFOException as E
from common_base.errors import AliveError
from common_base.constants import TMsgType


@processor(CMD.CMD_UGC_LIKE, internal_access=True)
class Like(BaseProcessor):
    """
    Like
    """
    
    TAG = 'Like'
    
    def __init__(self, handler):
        """
        Constructor
        """
        BaseProcessor.__init__(self, handler)

    def process(self):
        """
        process protocol
        """
        userid = self.alive_cmsdb.get_userid_by_userkey(self.user_key)
        if not userid:
            raise E(AliveError.ERROR_USER_DOES_NOT_EXIST)

        # 帖子是否存在
        article_info = self.alive_cmsdb.get_article_info_by_article_id(self.article_id)
        if not article_info:
            raise E(AliveError.ERROR_ARTICLE_DOES_NOT_EXIST)

        # 点赞者是否被帖子作者拉黑
        article_author_id = article_info['authorId']
        db_blocker = self.alive_cmsdb.get_blocker_by_condition(userid)
        blocker_ids = [e['blocker'] for e in db_blocker]
        if article_author_id in blocker_ids:
            raise E(AliveError.ERROR_BLOCKED_BY_THE_AUTHOR)

        # 是否已经点过赞
        do_i_liked = self.alive_cmsdb.judge_user_already_liked(userid, self.article_id)
        if do_i_liked:
            raise E(AliveError.ERROR_ALREADY_LIKED)

        # 保存点赞数据
        self.alive_cmsdb.save_like(self.article_id, userid)

        # TODO: 发送push(站内信)


        return dict()

    def like_notification(self, operator_id, article_author_id):
        """
        点赞站内信处理
        """
        # 维护T_ARTICLELIKE_HISTORY表数据
        v_hours = self.alive_cmsdb.get_like_msg_diff_hours(operator_id, self.article_id)
        if v_hours is None:
            # 插入T_ARTICLELIKE_HISTORY
            self.alive_cmsdb.save_article_like_history(operator_id, self.article_id)
        elif v_hours > 24:
            # 大于24小时(原有逻辑),更新LASTPUSHDATE
            self.alive_cmsdb.update_article_like_history_lash_push_date(operator_id, self.article_id)

        # 判断要不要发送push
        if operator_id != article_author_id and (v_hours is None or v_hours > 24):
            # 发送push
            pass

    def _verify_params(self):
        """
        重写父类方法, 作参数校验
        """
        self.article_id = self.params.get('articleId')
        if not self.article_id:
            raise ParamException('articleId')
